﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MonsterMove : MonoBehaviour
{
    public float mSpeed = 0.05f;
    
    private Vector3 mPointA;
    private Vector3 mPointB;
    private RaycastHit hitInfo;
    // Start is called before the first frame update
    void Start()
    {
        mPointA = this.transform.position;
        mPointB = mPointA + this.transform.right * 8;
        StartCoroutine(MoveToPosition());
    }

    // Update is called once per frame
    void Update()
    {
        this.transform.Rotate(new Vector3(0f, 10f, 0f));
        bool isHit = Physics.Raycast(this.transform.position, this.transform.forward, out hitInfo, 5f);
        if (isHit && hitInfo.transform.CompareTag("Player"))
        {
            GameObject _player = hitInfo.collider.gameObject;
            if (_player.GetComponentInChildren<Light>().enabled) Dead();
        }

    }

    IEnumerator MoveToPosition()
    {
        while(true)
        {
            while (this.transform.position != mPointB)
            {
                this.transform.position = Vector3.MoveTowards(this.transform.position, mPointB, mSpeed * Time.deltaTime);
                yield return 0;
            }

            while (this.transform.position != mPointA)
            {
                this.transform.position = Vector3.MoveTowards(this.transform.position, mPointA, mSpeed * Time.deltaTime);
                yield return 0;
            }
        }
        
    }

    private void Dead()
    {
        SceneManager.LoadScene("SampleScene");
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player")) Dead();
    }
}
